#!/bin/bash

[[ -n $DEBUG ]] && set -x
set -euo pipefail
IFS=$'\n\t'
prog=$(basename "$0")

date_fotmat='%Y-%m-%d %H:%M:%S'
pip_conf_dir="${HOME}/.pip"
pip_conf="${pip_conf_dir}/pip.conf"

_log() {
  echo "[$(date +"${date_fotmat}")]: $*"
}

_warn() {
  echo -e "\033[1;33m[$(date +"${date_fotmat}")]: $*\033[0m" >&2
}

_err() {
  echo -e "\033[1;31m[$(date +"${date_fotmat}")]: $*\033[0m" >&2
  exit 1
}

default_pip_conf=$(
  cat <<EOF
[global]
index-url = http://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host=mirrors.aliyun.com
EOF
)

# a list show all items needs to install by pipx
pipx_items=(
  "poetry"
  "uv"
)

uv_items=()

usage() {
  echo "============================="
  echo "Descption: $prog prepare my python enviroment."
  echo "Usage: $prog"
  echo "       $prog                                note: show help message"
  echo "       $prog help                           note: show help message"
  echo "       $prog check                          note: check all software need to install"
  echo "       $prog prepare                        note: start prepare enviroment"
  echo "============================="
}

pipx_install() {
  _log "execute: pipx install $@"
  if pipx list --short | grep -q "$@"; then
    :
  else
    pipx install "$@"
  fi
}

uv_install() {
  _log "execute: uv install $@"
  uv install "$@"
}

prepare() {
  _log "start prepare environment..."
  _log "pipx ensurepath"
  pipx ensurepath

  mkdir -p "${pip_conf_dir}"
  if [ -f "${pip_conf}" ]; then
    _log "${pip_conf} exist"
  else
    _log "$create {pip_conf}"
    echo "${default_pip_conf}" >"${pip_conf}"
  fi

  _log "> install pipx item:"
  local flag=0
  for target_item in "${pipx_items[@]}"; do
    pipx_install "${target_item}"
    flag=1
  done

  _log "> install uv item:"
  for target_item in "${uv_items[@]}"; do
    uv_install "${target_item}"
    flag=1
  done

  if [[ "${flag}" -eq 0 ]]; then
    _warn "there is no any software needs to install."
  else
    _log "prepare enviroment finish, check status..."
    check
  fi
}

check() {
  echo "================================================"
  echo "check python enviroment..."
  echo "================================================"
  if ! command -v pipx >/dev/null; then
    _err "pipx does not exist, please install it first"
  fi

  if [ ! -f "${pip_conf}" ]; then
    _info "${pip_conf} does not exist, execute '$proc config' can set config"
  fi

  echo "> target items managed by pipx:"
  for item in "${pipx_items[@]}"; do
    local query_result=$(pipx list --short | grep "^${item} ")
    if [ -z "${query_result}" ]; then
      echo -e "\033[1;31m[×] ${item}\033[0m" >&2
    else
      echo "[√] ${query_result#ii  }"
    fi
  done
}

main() {
  if [[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]]; then
    # show help
    usage
    exit 0
  fi
  case "$1" in
  "help" | "h") usage ;;
  "check") check ;;
  "prepare") prepare ;;
  *) usage ;;
  esac

}

main "$@"
